import Reflux from 'reflux';
import {Control} from "react-keeper";
import {Toast} from "antd-mobile";
import Actions from "./Actions";
import update from 'react-addons-update';
import DB from '../../../../app/db';
import StorageUtils from "../../../../app/storage";
import Utils from "../../../../utils/index";

export default Reflux.createStore({
  listenables: [Actions],
  data: {
    voteId: '',
    districtId: '',
    districtName: '',
    title: '',
    images: [],
    questions: [],
    suggestion: '',
    description: '',
    isVoted: false,
    canVote: true
  },

  init() {
    this.data.userInfo = update(this.data.userInfo, {$set: StorageUtils.getStorage().get('user')});
    this.updateComponent();
  },

  initVote() {
    this.initState(Control.state);
    this.getVoteResult();
  },

  getVoteResult() {

    let t = this;
    let proprietor = StorageUtils.getStorageItem('proprietor');
    let params = {
      proprietorId: proprietor.id,
      planId: Control.state.voteId,
      courtId: Control.state.id
    };
    DB.WechatAPI.getVoteResult(params).then(
      function (content) {
        if (content && content.vrList && content.vrList.length >0) {
          t.data.isVoted = true;
          t.data.suggestion = content.message;
          let qrList = content.vrList.map(vr => {
            return {
              id: vr.optionId,
              result: vr.result
            }
          });
          let questions = t.data.questions.map(q => {
            qrList.map(qr => {
              if (qr.id === q.id) {
                q = update(q, {result: {$set: qr.result}});
              }
            });
            return q;
          });
          t.data.questions = update(t.data.questions, {$merge: questions});
          t.updateComponent();
        }
      },
      function (error) {
        Utils.myAlert(error);
      }
    );
  },

  onInputChange(input) {
    this.data.suggestion = update(this.data.suggestion, {$set: input});
    this.updateComponent();
  },

  onOptionSelected(value, questionId) {
    this.data = update(this.data, {
      questions: {
        $apply: (questions) => {
          return questions.map(q => {
            if (q.id === questionId) {
              return update(q, {result: {$set: value}})
            } else {
              return q;
            }
          })
        }
      }
    });
    this.updateComponent();
  },

  initState(vote) {
    let t = this;
    // 获取方案图片
    DB.WechatAPI.getPlanImages({aId: vote.voteId}).then(
      function (content) {
        let images = [];
        if (content && content.length > 0) {
          content.map(img => {
            images.push(img.httpurl);
          })
        }
        t.data.images = images;
        t.updateComponent();
      },
      function (error) {
        console.log(error);
        t.data.images = [];
        t.updateComponent();
      }
    );

    // 获取问卷调查
    DB.WechatAPI.getQuestion({planid: vote.voteId}).then(
      function (content) {
        let questions = [];
        if (content && content.length > 0) {
          content.map(q => {
            questions.push({
              id: q.id,
              voteId: q.planid,
              text: q.detail,
              options: [
                {value: 1, label: q.agree},
                {value: 2, label: q.disagree}
              ],
              result: 1
            })
          })
        }
        t.data.questions = questions;
        t.updateComponent();
      },
      function (error) {
        console.log(error);
        t.data.questions = [];
        t.updateComponent();
      }
    );

    this.data = update(this.data, {
      voteId: {$set: vote.voteId},
      districtId: {$set: vote.id},
      districtName: {$set: vote.name},
      title: {$set: vote.name+"("+vote.title+")"},
      questions: {$set: []},
      suggestion: {$set: ''},
      description: {$set: vote.description},
      isVoted: {$set: false},
      canVote: {$set: true}
    });
    this.updateComponent();
  },

  // 投票
  onVote(data) {
    let proprietor = StorageUtils.getStorageItem('proprietor');
    let vrList = data.questions.map(r => {
      return {
        optionId: r.id,
        courtId: data.districtId,
        proprietorId: proprietor.id,
        result: r.result
      }
    });
    let result = {
      planId: data.voteId,
      courtId: data.districtId,
      proprietorId: proprietor.id,
      message: this.data.suggestion,
      vrList: vrList
    };
    DB.WechatAPI.doVote(result).then(
      function (content) {
        Toast.fail(content, 2);
        setTimeout(() => {
          Control.go('/home/vote/fa');
        }, 1500);
      },
      function (error) {
        console.log(error);
      }
    );
  },

  updateComponent: function () {
    this.trigger(this.data);
  },

  getInitialState() {
    return this.data;
  }
});
